package com.phkj.qdh.net

import okhttp3.Response
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.TypeParser
import rxhttp.wrapper.utils.convertTo
import java.io.IOException
import java.lang.reflect.Type


@Parser(name = "Response", wrappers = [PageList::class])
open class ResponseParser<T> : TypeParser<T> {
    protected constructor() : super()
    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: Response): T {
        //将okhttp3.Response转换为自定义的Response对象
        val data: BaseResponse<T> =
            response.convertTo(BaseResponse::class, *types) //这里的types就是自定义Response<T>里面的泛型类型
        val t: T? = data.data //获取data字段
        if (data.code != 0 || t == null) { //这里假设code不等0，代表数据不正确，抛出异常1为失败
//            if (data.code == 4001 && t != null) {
//                throw MFException(data.code.toString(), data.msg, t as String)
//            } else {
//
//            }
            throw ParseException(data.code.toString(), data.error, response)
        }
        return t
    }
}

class MFException(
    val code: String, val msg: String, val data: String
) : Exception()